// Description of what's in this file.
// @dart = 2.9

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutterappdriver/network/api_cache.dart';
import 'package:flutterappdriver/provider/video_controller.dart';
import 'package:flutterappdriver/routes/Routes.dart';
import 'package:flutterappdriver/provider/color_provider.dart';
import 'package:flutterappdriver/provider/music_controller.dart';
import 'package:flutterappdriver/utils/shared_preference_util.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

const _url = 'https://flutter.cn';

//

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  _initBeforeRunApp().then((value) {
    runApp(_buildProvider());
    _doSomethingInBackground();
    // _launchURL();
  });
}

void _launchURL() async =>
    await canLaunch(_url) ? await launch(_url) : throw 'Could not launch $_url';
/// 在启动之前要做的异步任务
/// 获取主题颜色
Future<bool> _initBeforeRunApp() async {
  // 要去SharedPrefrence里面去颜色数据，但是为异步任务，修改main方法，首先完成异步任务再启动app；
  await SharedPreferenceUtil.init();
  ColorStyleProvider.initColorStyle();

  // 设置安卓沉浸式状态栏
  // if (Platform.isAndroid) {
  //   // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
  //   SystemUiOverlayStyle systemUiOverlayStyle =
  //   SystemUiOverlayStyle(statusBarColor: Colors.transparent);
  //   SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  // }

  // 强制竖屏
  SystemChrome.setPreferredOrientations(
      [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);

  // 打开视觉调试开关
  //debugPaintSizeEnabled = true;
  return true;
}

/// 启动时要进行的后台任务
/// 这里简单用async，如果任务比较耗时，考虑Isolate方案。
_doSomethingInBackground() async {
  // 清理缓存
  await APICache.clearCache();
}

/// 遇到一个坑，一直报错：flutter Could not find the correct Provider
/// 原来是Provider要加在App上面，而不是HomePage上面。
_buildProvider() {
  return MultiProvider(
    providers: [
      ChangeNotifierProvider<ColorStyleProvider>.value(value: ColorStyleProvider()),
      ChangeNotifierProvider<MusicControllerProvider>.value(value: MusicControllerProvider()),
      ChangeNotifierProvider<VideoControllerProvider>.value(value: VideoControllerProvider()),
    ],
    child: RootPage(),
  );
}

class RootPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _RootPageState();
}

class _RootPageState extends State<RootPage> {
  @override
  Widget build(BuildContext context) {
    ColorStyleProvider colorStyleProvider =
        Provider.of<ColorStyleProvider>(context);
    return OKToast(
      child: ScreenUtilInit(
        designSize: Size(750, 1334),
        builder: () => MaterialApp(
          title: 'HKMusic',
          theme: ThemeData(
            brightness: Brightness.light,
            appBarTheme: AppBarTheme(
              brightness: Brightness.dark,
              iconTheme: IconThemeData(color: Colors.white),
              textTheme: TextTheme(title: TextStyle(color: Colors.white)),
            ),
            primarySwatch:
                colorStyleProvider.getCurrentColor(color: 'mainColor'),
          ),
          routes: Routes.routes,
          initialRoute: Routes.welcome_page,
          // 隐藏debug标识
          debugShowCheckedModeBanner: false,
          // 是否打开性能测试层
          showPerformanceOverlay: colorStyleProvider.showPerformanceOverlay,
        ),
      ),
      textPadding: EdgeInsets.only(
        left: 20,
        right: 20,
        top: 10,
        bottom: 10,
      ),
      radius: 12,
    );
  }
}
